package com.it.security.filter;

import com.it.security.utils.JwtAuthUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: learning
 * @description: jwt 整合 security
 * @author: Lefnmg
 * @create: 2018-11-19 16:49
 **/
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    JwtAuthUtils jwtAuthUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("token");
        Claims claims = jwtAuthUtils.getClaimByToken(token);
        if (claims != null && SecurityContextHolder.getContext().getAuthentication() == null && !jwtAuthUtils.isTokenExpired(claims.getExpiration())) {
            UserDetails user = jwtAuthUtils.getJWTUserByToken(claims);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info(String.format("Authenticated user %s, setting security context", claims.getSubject()));
            SecurityContextHolder.getContext().setAuthentication(authentication);

        }
        chain.doFilter(request, response);
    }
}
